package com.mkj.basic;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @Author Arrebol
 * @Date 2024/8/6 16:56
 * @Project graphical programming
 * @Description：
 * 文件选择器基本演示
 */
public class JFileChooserDemo {

    //创建窗口对象
    private final JFrame frame = new JFrame("测试文件选择器");
    //创建菜单条
    private JMenuBar menuBar = new JMenuBar();
    //创建菜单
    JMenu fileMenu = new JMenu("文件");
    JMenuItem openMenuItem = new JMenuItem(new AbstractAction("打开") {
        @Override
        public void actionPerformed(ActionEvent e) {
            //显示一个文件选择器
            JFileChooser fileChooser = new JFileChooser(".");
            fileChooser.showOpenDialog(frame);
            //获取用户选择的文件
            File selectedFile = fileChooser.getSelectedFile();
            //显示
            try {
                image = ImageIO.read(selectedFile);
                drawArea.repaint();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });
    JMenuItem saveMenuItem = new JMenuItem(new AbstractAction("另存为") {
        @Override
        public void actionPerformed(ActionEvent e) {
            //显示一个文件选择器
            JFileChooser fileChooser = new JFileChooser(".");
            fileChooser.showSaveDialog(frame);
            //获取用户选择的保存文件路径
            File selectedFile = fileChooser.getSelectedFile();
            //显示
            try {
                ImageIO.write(image,"jpeg",selectedFile);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });
    BufferedImage image;
    //swing提供的组件都是使用了图像缓冲区技术，其
    private class MyCanvas extends JPanel{
        @Override
        public void paint(Graphics g) {
            //将图片绘制到组件上
            g.drawImage(image,0,0,null);
        }
    }
    MyCanvas drawArea = new MyCanvas();

    public void init(){
        //组装视图
        fileMenu.add(openMenuItem);
        fileMenu.add(saveMenuItem);
        menuBar.add(fileMenu);
        frame.setJMenuBar(menuBar);
        drawArea.setPreferredSize(new Dimension(740,500));
        frame.add(drawArea);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        new JFileChooserDemo().init();
    }
}
